package com.lilihub.miaosha.rabbitmq;

import com.lilihub.miaosha.common.CodeMsg;
import com.lilihub.miaosha.common.Result;
import com.lilihub.miaosha.domain.MiaoshaOrder;
import com.lilihub.miaosha.domain.MiaoshaUser;
import com.lilihub.miaosha.domain.OrderInfo;
import com.lilihub.miaosha.service.GoodsService;
import com.lilihub.miaosha.service.MiaoshaService;
import com.lilihub.miaosha.service.OrderService;
import com.lilihub.miaosha.service.RedisService;
import com.lilihub.miaosha.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @BelongsProject: miaosha
 * @BelongsPackage: com.lilihub.miaosha.rabbitmq
 * @Author: LiYing
 * @CreateTime: 2021-04-28 20:16
 * @Description:
 */
@Service
public class MQRevicer {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private MiaoshaService miaoshaService;

    private static Logger log = LoggerFactory.getLogger(MQRevicer.class);


    @RabbitListener(queues = MQConfig.QUEUE)
    public void receive(String message){
        log.info("receive message :" + message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE_1)
    public void receiveTopic1(String message){
        log.info("receive topic1  message :" + message);
    }


    @RabbitListener(queues = MQConfig.TOPIC_QUEUE_2)
    public void receiveTopic2(String message){
        log.info("receive topic2 message :" + message);
    }

    @RabbitListener(queues = MQConfig.HEADERS_QUEUE)
    public void receiveHeaders(byte[] message){
        log.info("receive headers message :" + new String(message));
    }


    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receiveMiaoshaQueue(String message){
        log.info("receive message :" + message);

        MiaoshaMessage mm = RedisService.StringToBean(message, MiaoshaMessage.class);

        long goodsId = mm.getGoodsId();
        MiaoshaUser user = mm.getMiaoshaUser();

        // 4 请求出队，生成订单，减少库存
        GoodsVo goods = goodsService.getGoodsByGoodsId(goodsId);  //10 req1 req2
        Integer stockCount = goods.getStockCount();

        if (stockCount <= 0){
            return;
        }
        //判断用户是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(),goodsId);
        if (order != null){
            return;
        }

        //减库存 下订单 写入秒杀订单
        miaoshaService.miaosha(user,goods);



    }

}
